package userservice

import (
	"fmt"
	"go-web-admin/app/user/dao"
	usererror "go-web-admin/app/user/error"
	"go-web-admin/app/user/model/dto"
	"go-web-admin/app/user/model/entity"
	"go-web-admin/app/user/model/vo"
	common "go-web-admin/common/entity"
	"go-web-admin/jwt"
	"go-web-admin/utils"
)

type UserService struct {
	UserDao *userdao.UserDao
}

func NewUserService(userDao *userdao.UserDao) *UserService {
	return &UserService{
		UserDao: userDao,
	}
}

func (u *UserService) FindById(userId string) (*uservo.UserVo, error) {
	// 用户ID不能为空
	if userId == "" {
		return nil, usererror.UserIdEmpty
	}

	user := u.UserDao.FindById(userId)
	// 用户不存在
	if user == nil {
		return nil, usererror.UserNotFound
	}

	userVO := &uservo.UserVo{
		Id:       user.Id,
		Username: user.Username,
	}

	return userVO, nil
}

func (u *UserService) Register(reg *userdto.RegDto) (bool, error) {

	// 用户名不能重复
	user := u.UserDao.FindByUsername(reg.Username)
	if user != nil {
		return false, usererror.UsernameHasError
	}

	// 两次密码是否一致
	if reg.Password != reg.RePwd {
		return false, usererror.PwdNotRePwdError
	}

	// 密码加密
	hashPwd, _ := utils.HashPassword(reg.Password)

	// 保存用户信息
	userEntity := &userentity.User{
		Username: reg.Username,
		Password: hashPwd,
		Phone:    0,
		Status:   0,
	}

	// 初始化公共字段
	common.InitBaseEntity(&userEntity.BaseEntity)

	flag := u.UserDao.SaveUser(userEntity)

	return flag, nil
}

func (u *UserService) Login(loginDto userdto.LoginDto) (accessToken, refreshToken string, err error) {

	// 根据用户名查询
	user := u.UserDao.FindByUsername(loginDto.Username)
	if user == nil {
		return "", "", usererror.UnamePwdError
	}

	// 密码校验
	flag := utils.CheckPasswordHash(loginDto.Password, user.Password)
	if !flag {
		return "", "", usererror.UnamePwdError
	}

	// 创建Token
	accessToken, refreshToken, err = jwt.GenerateTokens(user.Id)
	fmt.Println("accessToken", accessToken)
	fmt.Println("refreshToke", refreshToken)
	if err != nil {
		return "", "", err
	}

	return accessToken, refreshToken, nil
}
